var $dataInfo = $('#dataInfo');
var rowCustomerId;
var membershipExpirationTm;//会员到期时间
//防止表头与表格不对齐
$(window).resize(function () {
    $dataInfo.bootstrapTable('resetView');
});

/**
 * 我的客户--页面初始化
 */
$(function () {
    // 会员合同时间
    $('#createTmStart').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
    }).on('changeDate',function(){
        console.log('start')
        var startDate = $('#createTmStart').val();
        $('#createTmEnd').datepicker('setStartDate', startDate);
    });
    $('#createTmEnd').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        // startDate: new Date(startDate)
    }).on('changeDate',function(){
        var endDate = $('#createTmEnd').val();
        $('#createTmStart').datepicker('setEndDate', endDate);
    });
    // 会员成交时间
    $('#transactionTmStart').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        // inputs: $('.range')
    }).on('changeDate',function(){
        var startDate = $('#transactionTmStart').val();
        $('#transactionTmEnd').datepicker('setStartDate', startDate);
    });
    $('#transactionTmEnd').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        // startDate: new Date(startDate)
    }).on('changeDate',function(){
        var endDate = $('#transactionTmEnd').val();
        $('#transactionTmStart').datepicker('setEndDate', endDate);
    });
    // 客户领取时间
    $('#receiveTmStart').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        // inputs: $('.range')
    }).on('changeDate',function(){
        var startDate = $('#receiveTmStart').val();
        $('#receiveTmEnd').datepicker('setStartDate', startDate);
    });
    $('#receiveTmEnd').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        // startDate: new Date(startDate)
    }).on('changeDate',function(){
        var endDate = $('#receiveTmEnd').val();
        $('#receiveTmStart').datepicker('setEndDate', endDate);
    });
    // 客户创建时间
    $('#creatCustomerTmStart').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        // inputs: $('.range')
    }).on('changeDate',function(){
        var startDate = $('#creatCustomerTmStart').val();
        $('#creatCustomerTmEnd').datepicker('setStartDate', startDate);
    });
    $('#creatCustomerTmEnd').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        // startDate: new Date(startDate)
    }).on('changeDate',function(){
        var endDate = $('#creatCustomerTmEnd').val();
        $('#creatCustomerTmStart').datepicker('setEndDate', endDate);
    });


    $('#screenWell select').selectpicker({
        size: 10,
        countSelectedText: function () {
            return '已选 {0} 条'
        }
    });


    // tab切换效果
    $('.new-tabs a').on('click', function () {
        lightyear.loading('show');  // 显示
        var tabType = $(this).data('value');
        $('#tabType').val(tabType);
        $(this).parents('li').addClass('active').siblings('li').removeClass('active');

        // 清空搜索框
        $('#customerNameMin').val('');

        if (tabType == 1) {
            // 客户领取时间 显示
            $('#receiveLabel').show();
            $('#creatCustomerLabel').hide();
        } else if (tabType == 3) {
            // 客户创建时间 显示
            $('#receiveLabel').hide();
            $('#creatCustomerLabel').show();
        } else {
            $('#receiveLabel, #creatCustomerLabel').hide();
        }

        // tab切换加载客户列表
        searchMyCustomerPool();
    });

    screenArea();
    screenIndustry();
    screenHotTag();

    //初始化我的客户列表
    dataInfoInit();
    //getToken();

    // 筛选展开关闭
    $('.filter-well > a').on('click', function () {
        $(this).prev('.row').slideToggle();
        if ($(this).hasClass('active')) {
            $(this).html('收起<i class="mdi mdi-chevron-up"></i>');
        } else {
            $(this).html('展开<i class="mdi mdi-chevron-down"></i>');
        }
        $(this).toggleClass('active');
    });
    $('#screenWell').find('select:not(#screenHotTag), .input-group input:not(.date-input)').on('change', function () {
        var section = $(this).parents('.input-group');
        // 区间人数输入框为空时不触发筛选
        if ($(this)[0].nodeName == 'SELECT' && section[0] && section.children('input.form-control').val() == '') {
            return;
        }
        tableScreen('dataInfo', esParams());
    });
    // 日期筛选条件
    $('#screenWell .date-input').datepicker().on('changeDate', function (e) {
        // console.log('change')
        tableScreen('dataInfo', esParams());
    });
    // 选择标签筛选条件
    var hotTagString = $('#screenHotTag').val() == null ? '' : $('#screenHotTag').val().toString();
    $('#screenHotTag').on('hidden.bs.select', function () {
        var selectedTagString = $('#screenHotTag').val() == null ? '' : $('#screenHotTag').val().toString();
        if (hotTagString != selectedTagString) {
            // console.log(hotTagString, selectedTagString)
            hotTagString = selectedTagString;
            tableScreen('dataInfo', esParams());
        }
    })

    // 标签弹窗
    $('#editTags').on('show.bs.modal', function () {
        tagsModal();
    });

    // 筛选条件省市区初始化
    getProvince();
});

// 渲染省市列表
function getProvince() {
    let provinceNames = ['<option value="" selected>不限</option>'];
    $.each(cityJson[0], function(key, value){
        provinceNames.push('<option value="' + key + '">' + value + '</option>');
    });
    $('#screenProvince').html(provinceNames.join(''));
    setTimeout(function () {
        $('#screenProvince').selectpicker('refresh');
    }, 100);
    getCity($('#screenProvince').val());
}
// 根据省获取市
function getCity(provinceId) {
    $('#city').html('');
    let key = '0,'+provinceId;
    let cityNames = ['<option value="" selected>不限</option>'];
    if(provinceId != ''){
        $.each(cityJson[key], function(key, value){
            cityNames.push('<option value="' + key + '">' + value + '</option>')
        });
    }
    $('#screenCity').html(cityNames.join(''));
    getOrangin($('#screenProvince').val(), $('#screenCity').val());
}
// 获取区
function getOrangin(provinceId, cityId) {
    $('#screenCounty').html('');
    let key = '0,'+provinceId+ ',' + cityId;
    let oranginNames = ['<option value="" selected>不限</option>'];
    if(provinceId != '' && cityId != ''){
        $.each(cityJson[key], function(key, value){
            oranginNames.push('<option value="' + key + '">' + value + '</option>')
        });
    }
    $('#screenCounty').html(oranginNames.join(''));
    $('#screenWell select').selectpicker('refresh');
}
// 切换省
function changeProvince() {
    getCity($('#screenProvince').val());
    getOrangin($('#screenProvince').val(), $('#screenCity').val());
}
// 切换城市
function changeCity() {
    getOrangin($('#screenProvince').val(), $("#screenCity").val());
}

/**
 * 功能：新增标签
 * */
function addTag (customerId, tag, index) {
    var jsonData = {
        customerId,    // 客户详情id
        tag,           // 标签
    };
    $.ajax({
        url: '/customer/updateCustomerImgAndTag',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $('#dataInfo').bootstrapTable('updateCell', {
                    index,
                    field: 'tag',
                    value: tag
                });
                tableNav();
            } else {

            }
        }),
        error: (function (err) {
            console.log(err)
        })
    });
}

/**
 * 功能：筛选条件回显
 * 参数：type-筛选条件行id  url-相关数据接口  dataType-筛选参数字段(data-tag)  nameType-筛选条件名称
 * */
function screenArea() {
    $.ajax({
        url: '/customerController/selectProvince',
        type: 'POST',
        datatype: 'json',
        async: true,
        data: {
            bs: 1,      // 0-管理端 1-用户端
        },
        success: function (data) {
            if (data.code == '000000') {
                var areaList = '<option value="">不限</option>';
                for (var i = 0; i < data.data.length; i++) {
                    areaList += '<option value="' + data.data[i].name + '">' + data.data[i].name + '</option>';
                }
                $('#screenArea').html(areaList);
                $('#screenArea').selectpicker('refresh');


                return
                if (data.data.length == 0) {
                    $('#' + type).hide();
                }
                $('#' + type).find('dt').nextAll('dd').remove();
                var screenList = '<dd><a href="JavaScript:void(0);" data-tag="" class="active">不限</a></dd>';
                for (var i = 0; i < data.data.length; i++) {
                    screenList += '<dd><a href="JavaScript:void(0);" data-tag="' + data.data[i][dataType] + '">' + data.data[i][nameType] + '</a></dd>';
                }
                $('#' + type).append(screenList);
                if (type == 'screenAreaRow') {
                    var areaList = '<option value="">请选择</option>';
                    for (var i = 0; i < data.data.length; i++) {
                        areaList += '<option value="' + data.data[i][dataType] + '">' + data.data[i][nameType] + '</option>';
                    }
                    $('#area').html(areaList);
                    $('#area').selectpicker({
                        noneSelectedText: '请选择',
                        sanitize: true,
                        size: 12,
                    });
                }

                // 超出一行设置展开收起按钮
                screenMoreAction(type);
            }
        }
    });
}
function screenIndustry() {
    $.ajax({
        url: '/customerController/selectIndustry',
        type: 'POST',
        datatype: 'json',
        async: true,
        data: {
            bs: 1,      // 0-管理端 1-用户端
        },
        success: function (data) {
            if (data.code == '000000') {
                var industryList = '<option value="">不限</option>';
                for (var i = 0; i < data.data.length; i++) {
                    industryList += '<option value="' + data.data[i].code + '">' + data.data[i].name + '</option>';
                }
                $('#screenIndustry').html(industryList);
                $('#screenIndustry').selectpicker('refresh');
            }
        }
    });
}
function screenHotTag() {
    $.ajax({
        // url: '/customerController/selectTag',
        url: '/customerController/selectTagAndCustomizeTag',
        type: 'POST',
        datatype: 'json',
        async: true,
        data: {
            bs: 1,      // 0-管理端 1-用户端
        },
        success: function (data) {
            if (data.code == '000000') {
                var customTag = data.data['客户自定义标签'];
                var shortcutTag = data.data['客户快捷标签'];
                // console.log(customTag, shortcutTag);
                var tagsDom = '';
                if (customTag.length == 0 && shortcutTag.length == 0) {
                    var singleTags = customTag.length == 0 ? shortcutTag : customTag;
                    if (singleTags.length) {
                        tagsDom = '<option value="">不限</option>';
                        for (let i = 0; i < singleTags.length; i++) {
                            tagsDom += '<option value="' + singleTags[i].tag + '">' + singleTags[i].tag + '</option>';
                        }
                    } else {
                        tagsDom = '<option value="">不限</option>';
                    }
                } else {
                    var customTagDom = '<optgroup label="自定义快捷标签">';
                    for (let i = 0; i < customTag.length; i++) {
                        customTagDom += '<option value="' + customTag[i].tag + '">' + customTag[i].tag + '</option>';
                    }
                    customTagDom += '</optgroup>';

                    var shortcutTagDom = '<optgroup label="客户快捷标签">';
                    for (let i = 0; i < shortcutTag.length; i++) {
                        shortcutTagDom += '<option value="' + shortcutTag[i].tag + '">' + shortcutTag[i].tag + '</option>';
                    }
                    shortcutTagDom += '</optgroup>';
                    tagsDom = shortcutTagDom + customTagDom;
                }
                /*var tagList = '<option value="">不限</option>';
                for (var i = 0; i < data.data.length; i++) {
                    tagList += '<option value="' + data.data[i].tag + '">' + data.data[i].tag + '</option>';
                }*/
                $('#screenHotTag').html(tagsDom);
                $('#screenHotTag').selectpicker('refresh');
            }
        }
    });
}

function screenData() {
    $('#screenBox').children('dl').each(function () {
        var type = $(this).prop('id');
        var url, dataType, nameType;
        switch (type) {
            case 'screenAreaRow':       // 地区
                url = '/customerController/selectProvince';
                nameType = 'name';
                dataType = 'name';
                break;
            case 'screenIndustryRow':   //行业
                url = '/customerController/selectIndustry';
                nameType = 'name';
                dataType = 'code';
                break;
            case 'screenHotTagRow':     //热门标签
                url = '/customerController/selectTag';
                nameType = 'tag';
                dataType = 'tag';
                break;
            case 'screenFollowTagRow':  //跟进标签
                url = '/customerController/selectFollowTag';
                nameType = 'tag';
                dataType = 'tag';
                break;
        }
        $.ajax({
            url,
            type: 'POST',
            datatype: 'json',
            async: true,
            data: {
                bs: 1,      // 0-管理端 1-用户端
            },
            success: function (data) {
                if (data.code == '000000') {
                    if (data.data.length == 0) {
                        $('#' + type).hide();
                    }
                    $('#' + type).find('dt').nextAll('dd').remove();
                    var screenList = '<dd><a href="JavaScript:void(0);" data-tag="" class="active">不限</a></dd>';
                    for (var i = 0; i < data.data.length; i++) {
                        screenList += '<dd><a href="JavaScript:void(0);" data-tag="' + data.data[i][dataType] + '">' + data.data[i][nameType] + '</a></dd>';
                    }
                    $('#' + type).append(screenList);
                    if (type == 'screenAreaRow') {
                        var areaList = '<option value="">请选择</option>';
                        for (var i = 0; i < data.data.length; i++) {
                            areaList += '<option value="' + data.data[i][dataType] + '">' + data.data[i][nameType] + '</option>';
                        }
                        $('#area').html(areaList);
                        $('#area').selectpicker({
                            noneSelectedText: '请选择',
                            sanitize: true,
                            size: 12,
                        });
                    }

                    // 超出一行设置展开收起按钮
                    screenMoreAction(type);
                }
            }
        });
    })
}

// 超出一行设置展开收起按钮
function screenMoreAction(id) {
    var $dl = $('#' + id);
    var rowHeight = $dl.height();
    var moreBtn = '<dd class="more"><a href="JavaScript:void(0);"><i class="mdi mdi-chevron-double-down"></i>展开</a></dd>';
    if (rowHeight > 34) {
        $dl.addClass('row-more').append(moreBtn);
        $dl.on('click', 'dd.more', function () {
            if ($dl.hasClass('row-more')) {
                $dl.removeClass('row-more').find('dd.more a').html('<i class="mdi mdi-chevron-double-up"></i>收起');
            } else {
                $dl.addClass('row-more').find('dd.more a').html('<i class="mdi mdi-chevron-double-down"></i>展开');
            }
        });
    }
}

/**
 * 功能：筛选条件(地区、行业、热门、跟进标签、日期)
 * 参数：
 * tabType: 0-全部 1-我领取的 2-分配给我的 3-我自建的 4-意向客户 5-新单客户 6-续费客户 7-流失客户 8-个人客户
 * dateType: all-全部 week-本周 month-本月 year-本年
 * */
function paramsData(type) {
    getToken();
    var params = {};
    params.authorization = tokenVal;
    params.accountId = $('#accountId').val();
    params.tabType = $('#tabType').val();                               // bab类型
    params.provinceCode = $('#screenArea').val();                       // 地区
    params.followStatus = $('#followStatus').val();                     // 跟进状态
    params.hotTag = $('#screenHotTag').val();                           // 热门标签
    params.followTag = $('#screenFollowTag').val();                     // 跟进标签
    params.memberExpTime = $('#memberExpTime').val();                   // 会员到期时间
    params.memberType = $('#memberType').val();                         // 会员类型
    params.memberContractStartTime = $('#createTmStart').val();
    params.memberContractEndTime = $('#createTmEnd').val();
    params.memberDealStartTime = $('#memberDealStartTime').val();
    params.memberDealEndTime = $('#memberDealEndTime').val();
    params.dateType = $('.select-switch input:checked').val();          // 时间切换(全部、本周、本月、本年)
    if (type == 'basics') { // 基础搜索
        params.customerName = $('#customerNameMin').val();
    }
    if (type == 'senior') { // 高级搜索
        params.customerName = $('#customerName').val();
        params.tag = $('#tag').val();
        params.createTmStart = $('#createTmStart').val();
        params.createTmEnd = $('#createTmEnd').val();
        var contactPersonCount = $('#contactPersonCountInp').val();
        if(contactPersonCount){//联系人数量
            var operator = $('#contactPersonCountSel option:selected').val();
            params.contactPersonCountOperator = operator;
            params.contactPersonCount = contactPersonCount;
        }
        var financialNumber = $('#financialNumberInp').val();
        if(financialNumber){//财务人数
            var operator = $('#financialNumberSel option:selected').val();
            params.financialNumberOperator = operator;
            params.financialNumber =  financialNumber;
        }
        var insuredNumber = $('#insuredNumberInp').val();
        if(insuredNumber){//参保人数
            var operator = $('#insuredNumberSel option:selected').val();
            params.insuredNumberOperator = operator;
            params.insuredNumber = insuredNumber;
        }
        var registeredCapital = $('#registeredCapitalInp').val();
        if(registeredCapital){//注册资本
            var operator = $('#registeredCapitalSel option:selected').val();
            params.registeredCapitalOperator = operator;
            params.registeredCapital = registeredCapital;
        }

        params.companySize = $('#companySizeSel option:selected').val();//公司规模
        params.provinceCode = $('#area').val();//地区
        params.memberType = $('#memberType').val(); // 会员类型
        params.memberExpTime = $('#memberExpTime').val(); // 会员到期时间
    }
    return params;
}

function esParams() {
    // 获取token
    getToken();
    var params = {};
    var province = $('#screenProvince option:selected').text().split('省').join('');
    var city = $('#screenCity option:selected').text().split('市').join('');
    var county = $('#screenCounty option:selected').text();

    params.authorization = tokenVal;
    params.accountId = $('#accountId').val();
    params.customerName = $('#customerNameMin').val();                  // 搜索框数据
    params.tabType = $('#tabType').val();                               // bab类型
    params.followStatus = $('#followStatus').val();                     // 跟进状态
    params.industry = $('#screenIndustry').val();                       // 所在行业
    // params.provinceCode = $('#screenProvince option:selected').text() == '不限' ? '' : $('#screenProvince option:selected').text();  // 省
    // params.cityCode = $('#screenCity option:selected').text() == '不限' ? '' : $('#screenCity option:selected').text();  // 市
    // params.countyCode = $('#screenCounty option:selected').text() == '不限' ? '' : $('#screenCounty option:selected').text();  // 区县
    params.provinceCode = province == '不限' ? '' : province;             // 省
    params.cityCode = city == '不限' ? '' : city;                         // 市
    params.countyCode = county == '不限' ? '' : county;                   // 区县


    params.screenActivities = $('#screenActivities').val();             // 参加活动
    // 财务人数
    var financialNumber = $('#financialNumberInp').val();
    if(financialNumber){
        params.financialNumberOperator = $('#financialNumberSel option:selected').val();
        params.financialNumber =  financialNumber;
    }
    params.hotTag = $('#screenHotTag').val() == null ? '' : $('#screenHotTag').val().toString();   // 热门标签
    // 联系人数量
    var contactPersonCount = $('#contactPersonCountInp').val();
    if(contactPersonCount){
        params.contactPersonCountOperator = $('#contactPersonCountSel option:selected').val();;
        params.contactPersonCount = contactPersonCount;
    }
    // 参保人数
    var insuredNumber = $('#insuredNumberInp').val();
    if(insuredNumber){
        params.insuredNumberOperator = $('#insuredNumberSel option:selected').val();
        params.insuredNumber = insuredNumber;
    }
    params.memberContractStartTime = $('#createTmStart').val();         // 会员合同-开始时间
    params.memberContractEndTime = $('#createTmEnd').val();             // 会员合同-结束时间
    params.memberDealStartTime = $('#transactionTmStart').val();        // 会员成交-开始时间
    params.memberDealEndTime = $('#transactionTmEnd').val();            // 会员成交-结束时间
    params.receiveTmStart = $('#receiveTmStart').val();                 // 客户领取时间-开始时间
    params.receiveTmEnd = $('#receiveTmEnd').val();                     // 客户领取时间-结束时间
    params.createTmStart = $('#creatCustomerTmStart').val();            // 客户创建时间-开始时间
    params.createTmEnd = $('#creatCustomerTmEnd').val();                // 客户创建时间-结束时间
    params.memberExpTime = $('#memberExpTime').val();                   // 会员到期时间
    params.memberType = $('#memberType').val();                         // 会员类型

    return params;
}

/**
 * 功能：通用筛选方法
 * 参数：targetTableId:目标表格id  data:筛选条件
 * */
function tableScreen(targetTableId, data) {
    var $tableElement = $('#' + targetTableId);
    $tableElement.bootstrapTable('refreshOptions', {
        pageNumber: 1,
        queryParams: function (params) {
            // 获取token
            getToken();
            params.pageSize = params.limit;
            params.pageIndex = (params.offset / params.limit) + 1;
            params.sortName = params.sort;
            params.sortOrder = params.order;
            for (var key in data) {
                params[key] = data[key];
            }
            return params;
        }
    });
}
var tokenVal;
function getToken () {
    $.ajax({
        url: $('#esurl').val()+"/token/getToken",
        //url: 'http://localhost:8089/token/getToken',
        //url: 'https://cx.dcrm.cn/token/getToken',
        data: {
            accountId: $('#accountId').val()
        },
        type: 'POST',
        async: false,
        //dataType: "json",
        success: (function (data) {
            if(data.code == "200"){
                tokenVal = data.data;
                //dataInfoInit(tokenVal);
            }
        }),
        error: (function () {

        })
    })
}
/**
 * 我的客户
 */
function dataInfoInit() {
    //先销毁表格
    $dataInfo.bootstrapTable('destroy');
    $dataInfo.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: $('#esurl').val()+"/cutomer/selectListByPage",
        //url: "http://localhost:8089/cutomer/selectListByPage",
        //url: '/customerController/userCustomerList',//请求地址
        method: 'post',                                         // 请求方式
        contentType: "application/x-www-form-urlencoded",       // 请求内容类型
        dataType: "json",                                       // 数据类型
        striped: true,                                          // 是否显示行间隔色
        sortable: true,                                         // 是否启用排序
        sortOrder: "desc",                                      // 排序方式
        sortName: 'createTm',                                   // 排序字段
        cache: false,                                           // 是否使用缓存
        showColumns: false,                                     // 显示隐藏列
        showRefresh: false,                                     // 显示刷新按钮
        showToggle: false,                                      // 切换显示样式
        showFooter: false,                                      // 显示Table脚部
        pagination: true,                                       // 是否显示分页
        showPaginationSwitch: false,                            // 是否显示分页按钮
        clickToSelect: false,                                   // 是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,                                 // 最少要显示的列数
        undefinedText: '-',                                      // cell没有值时显示
        sidePagination: "server",                               // 分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerId',
        idField: 'customerId',
        pageSize: globalPageSize,                               // 每页的记录行数
        pageNumber: 1,                                          // 初始化加载第1页，默认第1页
        pageList: globalPageList,                               // 可供选择的每页的行数

        // detailView: true,                                       // 父子表
        // detailFormatter: detailFormatter,                       // 定义详情显示函数
        // detailViewIcon: false,                                  // 隐藏图标列
        // detailViewByClick: true,                                // 隐藏图标列

        fixedColumns: true,     // 冻结列
        fixedNumber: 2,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列
        // showFullscreen: true,
        queryParams: function (params) {
            getToken();
            params.pageSize = params.limit;
            params.pageIndex = (params.offset / params.limit) + 1;
            params.sortName = params.sort;
            params.sortOrder = params.order;

            params.authorization = tokenVal;
            params.accountId = $('#accountId').val();
            params.customerName = $('#customerNameMin').val();                  // 搜索框数据
            params.tabType = $('#tabType').val();                               // bab类型
            params.followStatus = $('#followStatus').val();                     // 跟进状态
            params.industry = $('#screenIndustry').val();                       // 所在行业
            params.provinceCode = $('#screenProvince option:selected').text() == '不限' ? '' : $('#screenProvince option:selected').text();  // 省
            params.cityCode = $('#screenCity option:selected').text() == '不限' ? '' : $('#screenCity option:selected').text();  // 市
            params.countyCode = $('#screenCounty option:selected').text() == '不限' ? '' : $('#screenCounty option:selected').text();  // 区县
            params.screenActivities = $('#screenActivities').val();             // 参加活动
            // 财务人数
            var financialNumber = $('#financialNumberInp').val();
            if(financialNumber){
                params.financialNumberOperator = $('#financialNumberSel option:selected').val();
                params.financialNumber =  financialNumber;
            }
            params.hotTag = $('#screenHotTag').val();                           // 热门标签
            // 联系人数量
            var contactPersonCount = $('#contactPersonCountInp').val();
            if(contactPersonCount){
                params.contactPersonCountOperator = $('#contactPersonCountSel option:selected').val();;
                params.contactPersonCount = contactPersonCount;
            }
            // 参保人数
            var insuredNumber = $('#insuredNumberInp').val();
            if(insuredNumber){
                params.insuredNumberOperator = $('#insuredNumberSel option:selected').val();
                params.insuredNumber = insuredNumber;
            }
            params.memberContractStartTime = $('#createTmStart').val();         // 会员合同-开始时间
            params.memberContractEndTime = $('#createTmEnd').val();             // 会员合同-结束时间
            params.memberDealStartTime = $('#transactionTmStart').val();        // 会员成交-开始时间
            params.memberDealEndTime = $('#transactionTmEnd').val();            // 会员成交-结束时间
            params.receiveTmStart = $('#receiveTmStart').val();                 // 客户领取时间-开始时间
            params.receiveTmEnd = $('#receiveTmEnd').val();                     // 客户领取时间-结束时间
            params.creatCustomerTmStart = $('#creatCustomerTmStart').val();     // 客户创建时间-开始时间
            params.creatCustomerTmEnd = $('#creatCustomerTmEnd').val();         // 客户创建时间-结束时间
            params.memberExpTime = $('#memberExpTime').val();                   // 会员到期时间
            params.memberType = $('#memberType').val();                         // 会员类型

            return params;
        },
        columns: [
            {title: '主键', field: 'customerId', visible: false},
            {title: '', field: 'accessUrl', align: 'center', valign: 'middle', width: '72',
                formatter:function(value,row,index){
                    // 解决用户名为null时切割字符串报错问题
                    var customerName = row.customerName || '';
                    var errorTip = '';
                    if (row.memberErrorData == 1) {
                        errorTip = '<em class="error-tips">错误数据</em>';
                    }
                    var accessUrl = row.accessUrl;
                    if(accessUrl){
                        return '<span class="head"><img src=' + accessUrl + '></span>' + errorTip;
                    }
                    return '<span class="head">' + customerName.split('')[0] + '</span>' + errorTip;
                }
            },
            {title: '客户名称', field: 'customerName', align: 'left', valign: 'middle', width: '120',
                formatter: function prompt(value, row, index) {
                    if(row.memberErrorData == 1) {
                        return '<a href="#!" onclick="errorData();">' + value + '</a>';
                    } else {
                        //if(row.customerType == 1){//个人客户
                        //return '<a href="#!" onclick="contactNameDetail(\'' + row.customerName + '\',\'' + row.contactPersonPhone + '\', \'' + row.customerId + '\')">'+value+'</a>';
                        //}else{//企业客户
                        return '<a href="#!" onclick=customerDetail("' + row.customerId + '")>'+value+'</a>';
                        //}
                    }
                }
            },
            {title: '所在地区', field: 'provinceName', align: 'left', valign: 'middle', width: '80',
                formatter: function (value, row) {
                    var provinceName = (row.provinceName == '--请选择--' || row.provinceName == null || row.provinceName == '') ? '' : row.provinceName;
                    var cityName = (row.cityName == '--请选择--' || row.cityName == null || row.cityName == '') ? '' : (' - ' + row.cityName);
                    var countyName = (row.countyName == '--请选择--' || row.countyName == null || row.countyName == '') ? '' : (' - ' + row.countyName);

                    var region = provinceName + cityName + countyName;
                    if (region.length > 15) {
                        return '<span data-toggle="tooltip" data-placement="top" data-original-title="' + region + '">' + region.slice(0, 15) + '...</span>';
                    } else {
                        return (provinceName + cityName + countyName) || undefined;
                    }
                }
            },
            /*{title: '联系人数量', field: 'contactPersonCount', align: 'center', valign: 'middle', width: '100'},
            {title: '竞品数量', field: 'competitorCount', align: 'center', valign: 'middle', width: '100'},*/
            {title: '客户类型', field: 'customerType', align: 'left', valign: 'middle', width: '100', formatter: customerTypeFormat},
            {title: '到期时间', field: 'membershipExpirationTm', align: 'left', valign: 'middle', width: '100', visible: false,
                formatter: function (value, row) {
                    return value ? value.split(' ')[0] : undefined;
                }
            },
            {title: '标签', field: 'tag', align: 'left', valign: 'middle', events: operateEvents,
                formatter: function (value) {
                    let html;
                    if (value != null && value != '' && value != undefined) {
                        html = '<span class="tags-tip"><i class="mdi mdi-plus"></i><span>双击添加标签</span></span>';
                        let tagsArr = value.split(',').reverse();
                        for (let i = 0; i < tagsArr.length; i++) {
                            if (i > 9) {
                                break;
                            }
                            html += '<span class="label label-outline-warning">' + tagsArr[i] + '<i class="mdi mdi-close delete-tag"></i></span>';
                        }
                    } else {
                        html = '<span class="tags-tip"><i class="mdi mdi-plus"></i> 双击添加标签</span>';
                    }
                    return html;
                }
            },
            {title: '操作', field: 'operate', align: 'right', width: '250', events: operateEvents, formatter: genderOpt},
            {title: '客户状态', field:'customerState', visible: false}
        ],
        responseHandler: function (result) {
            if (result.code == "200") {
                var obj = {
                    "rows": result.data.list,
                    "total": result.data.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onDblClickCell: function(field, value, row, $element) {
            if (field == 'tag') {
                var index = $element.parents('tr').index();
                if (value == '' || value == null || value == undefined) {
                    var initialTags = '';
                } else {
                    var initialTags = value + ',';
                }
                $.ajax({
                    url: '/customerTagsController/tagList',
                    type: 'POST',
                    datatype: 'json',
                    data: {
                        pageSize: 10,
                        pageIndex: 1,
                    },
                    success: function (data) {
                        if (data.code == '000000') {
                            var generalTags = '';
                            for (let i = 0; i < data.data.length; i++) {
                                generalTags += '<label><input type="checkbox" value="' + data.data[i].tag + '"><span>' + data.data[i].tag + '</span></label>';
                            }
                            if (data.data == 0) {
                                generalTags = '<div class="no-tags">暂无快捷标签</div>';
                            }
                            $('#generalTags').html(generalTags);
                        }
                    }
                });
                $.confirm({
                    columnClass: 'col-md-5 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1',
                    keyboardEnabled: true,
                    confirmKeys: [13], // ENTER key
                    cancelKeys: [27], // ESC key
                    title: '快捷标签',
                    content: '' +
                        '<form action="" class="formName">' +
                        '<div id="generalTags" class="clearfix general-tags"></div>' +
                        '<h3>自定义标签</h3>' +
                        '<div class="form-group">' +
                        '<input type="text" placeholder="请输入标签名称，不多于5个字符" value="" class="tag-name form-control" autofocus required>' +
                        '</div>' +
                        '</form>',
                    buttons: {
                        cancel: {
                            text: '取消',
                            btnClass: 'btn-link'
                        },
                        formSubmit: {
                            text: '添加',
                            btnClass: 'btn-success',
                            action: function (e) {
                                var selectGeneralTags = '';
                                for (let i = 0; i < $('#generalTags input:checked').length; i++) {
                                    selectGeneralTags += $('#generalTags input:checked')[i].value + ',';
                                }
                                var tagInput = this.$content.find('.tag-name');
                                var newTag = tagInput.val();
                                var tagsArr = (initialTags + selectGeneralTags + newTag).split(',').filter(function (s) {
                                    return s && s.trim();
                                });
                                if(!newTag && !selectGeneralTags){
                                    $.alert({
                                        title: '系统提醒',
                                        content: '请选择或输入标签内容！'
                                    });
                                    return false;
                                }
                                if (newTag.length > 5) {
                                    $.alert({
                                        title: '系统提醒',
                                        content: '标签长度不能超过五个字符，请重新输入！'
                                    });
                                    return false;
                                }
                                addTag(row.customerId, [...new Set(tagsArr)].toString(), index);
                            }
                        },
                    },
                });
            }
        },
        onLoadSuccess: function () {
            // console.log('onLoadSuccess');
            // 会员标签显示到期时间
            if ($('#tabType').val() == '10') {
                $dataInfo.bootstrapTable('showColumn', 'membershipExpirationTm');
            } else {
                $dataInfo.bootstrapTable('hideColumn', 'membershipExpirationTm');
            }

            // table操作列下拉菜单效果
            tableNav();
            lightyear.loading('hide');  // 隐藏
        },
        onPostBody: function () {
            // console.log('onPostBody');
            $('[data-toggle="tooltip"]').tooltip();
        },
        onLoadError: function (status) {
            if (status == 403) {
                $.alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                $.alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

function errorData() {
    $.alert({
        title: '温馨提示',
        content: '该条数据您无权查看，请联系管理员！',
    })
}

/**
 * 功能：注册加载子表的事件
 * 参数：index:父表当前行的行索引  row:父表当前行的Json数据对象   $detail:当前行下面创建的新行里面的td对象
 * 说明：第三个参数尤其重要，因为生成的子表的table在装载在$detail对象里面的。bootstrap table为我们生成了$detail这个对象，然后我们只需要往它里面填充我们想要的table即可。
 * */
function detailFormatter(index, row, $detail) {
    initSubTable(index, row, $detail);
}

//初始化子表格(无线循环)
initSubTable = function (index, row, $detail) {
    var customerId = row.customerId;
    var cur_table = $detail.html('<table><caption>竞品列表</caption></table>').find('table');
    $(cur_table).bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerController/competitorList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'competitorId',
        idField: 'competitorId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            var temp = {
                pageSize: params.limit,                         //页面大小
                pageIndex: (params.offset / params.limit) + 1,   //页码
                sortName: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                customerId :customerId
            };
            return temp;
        },
        columns: [
            {title: '主键', field: 'competitorId', visible: false},
            {title: '序号', field: 'index', align: 'left', width: '60', valign: 'middle', formatter: indexFormat},
            {title: '产品名称',field: 'productName',align: 'left', valign: 'middle'},
            {title: '竞品名称', field: 'competitorName',  align: 'left', valign: 'middle'},
            {title: '产品价格', field: 'productPrice', align: 'left', valign: 'middle'},
            {title: '竞品价格',field: 'competitorPrice',align: 'left', valign: 'middle'},
            {title: '竞品单位', field: 'competitorUnit',  align: 'left', valign: 'middle'},
            {title: '竞品到期时间', field: 'competitorDueTime', align: 'left', valign: 'middle'},
            {title: '当前预算',field: 'currentBudget',align: 'left', valign: 'middle'},
            {title: '预算负责人', field: 'budgetDirector',  align: 'left', valign: 'middle',
                formatter: function (value, row) {
                    return value + '<button class="btn btn-default"><i class="mdi mdi-phone"></i>联系</button>'
                }
            },
            // {title: '负责人联系方式', field: 'directorInformation', align: 'left', valign: 'middle'},
            // {title: '创建时间',field: 'createTm',align: 'left', valign: 'middle'}/
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
        //无线循环取子表，直到子表里面没有记录
        onExpandRow: function (index, row, $Subdetail) {
            initSubTable(index, row, $Subdetail);
        }
    });
};

/**
 * 列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 我的客户--客户类型(0企业客户 1个人客户)
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerTypeFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "<span class='label label-info-light'>企业客户</span>";
    } else if (1 == value) {
        return "<span class='label label-warning-light'>个人客户</span>";
    }
}

/**
 * 我的客户--自定义操作列内容
 */
function genderOpt(value, row, index) {
    if (row.memberErrorData == 1) { // 错误数据操作功能添加申请修改
        return '<button type="button" class="btn btn-default">申请修改</button>'
    }
    let html = '';
    // 意向客户 potentialCustomers: 0-无意向  1-有意向
    if ($('#tabType').val() == '0') {
        // 非意向客户标签
        if (row.potentialCustomers == 1) {
            html += '<button class="btn btn-default btn-danger" id="removePotential"><i class="mdi mdi-delete-empty"></i>移除意向</button>';
        } else {
            html += '<button class="btn btn-default" id="addPotential"><i class="mdi mdi-clipboard-check"></i>设为意向</button>';
        }
    }

    html += '<button class="btn btn-default" id="toAddOpportunity"><i class="mdi mdi-telegram"></i>转商机</button>';

    // 个人客户-删除按钮
    /*if ($('#tabType').val() == 8) {
        html += '<button type="button" class="btn btn-default" id="delCustomer"><i class="mdi mdi-delete"></i>删除</button>';
    }*/
    html += '<div class="dropdown">';
    html += '<button type="button" id="followUp" class="btn btn-default" data-index="' + index + '"><i class="mdi mdi-image-filter-tilt-shift"></i>跟进</button>';
    html += '<ul class="dropdown-menu">';
    html += '<li><a href="JavaScript:void(0);" onclick="callCenter(\''+row.customerId+'\',\''+row.customerType+'\')">线上电话</a></li>';
    html += '<li><a href="JavaScript:void(0);" onclick="goOnline(\'offline\', \''+row.customerId+'\',\''+row.customerType+'\',\''+row.customerName+'\',\''+row.contactPersonPhone+'\')">线下电话</a></li>';
    html += '<li><a href="JavaScript:void(0);" onclick="goOnline(\'visit\', \''+row.customerId+'\',\''+row.customerType+'\',\''+row.customerName+'\',\''+row.contactPersonPhone+'\')">拜访</a></li>';
    html += '<li><a href="JavaScript:void(0);" onclick="goOnline(\'WeChat\', \''+row.customerId+'\',\''+row.customerType+'\',\''+row.customerName+'\',\''+row.contactPersonPhone+'\')">微信交流</a></li>';
    html += '<li><a href="JavaScript:void(0);" onclick="goOnline(\'accompanyingVisit\', \''+row.customerId+'\',\''+row.customerType+'\',\''+row.customerName+'\',\''+row.contactPersonPhone+'\')">陪访</a></li>';
    html += '<li><a href="JavaScript:void(0);" onclick="goOnline(\'email\', \''+row.customerId+'\',\''+row.customerType+'\',\''+row.customerName+'\',\''+row.contactPersonPhone+'\')">电子邮件</a></li>';
    html += '</ul>';
    html += '</div>';

    //html += '<button class="btn btn-default" id="move" style="width: 76px;"><i class="mdi mdi-transfer"></i>移动到</button>';
    if (row.membershipLevel > 0) {
        // 会员客户
    } else {
        // 非会员客户
        html += '<button class="btn btn-default btn-danger" id="release"><i class="mdi mdi-reply"></i>释放</button>';
    }

    // 意向客户 potentialCustomers: 0-无意向  1-有意向
    if ($('#tabType').val() == '4') {
        // 意向客户标签
        html += '<button class="btn btn-default btn-danger" id="removePotential"><i class="mdi mdi-delete-empty"></i>移除</button>';
    }
    return html;
}

/**
 * 我的客户--自定义操作列事件
 * @type {{"click #release": Window.operateEvents.click #release}}
 */
window.operateEvents = {
    // 删除标签
    'click .delete-tag': function (e, value, row, index) {
        $.alert({
            title: '删除提醒',
            content: '是否要删除此标签？',
            buttons: {
                cancel: {
                    text: '取消',
                    btnClass: 'btn-link'
                },
                confirm: {
                    text: '删除',
                    btnClass: 'btn-danger',
                    action: function () {
                        var targetTag = $(e.target).parent().prop('firstChild').nodeValue;
                        // var tags = row.tag;
                        var tagsArr = row.tag.split(',');
                        // 删除数组
                        remove(targetTag, tagsArr);
                        // 删除后的标签集合
                        var newTags = tagsArr.toString();
                        addTag(row.customerId, newTags, index);
                    }
                }
            }
        })
    },
    // 个人客户-删除
    'click #delCustomer': function (e, value, row, index) {
        deleteCustomer(row.customerId);
    },

    // 转商机-跳转到“商机管理-商机列表-新增商机页面并且默认‘客户名称’”
    'click #toAddOpportunity': function (e, value, row, index) {
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : '新增商机',
            url : "/front/opportunityManager/addOpportunity?opportunityBs=4&customerId=" + row.customerId + "&customerName=" + row.customerName // opportunityBs=4 表示从我的客户转到新增商机页面
        }, true);
    },
    // 释放
    'click #release': function (e, value, row, index) {
        $('#releaseReason').val('');
        $('#releaseCustomerModal').modal('show');
        rowCustomerId = row.customerId;
        membershipExpirationTm = row.membershipExpirationTm;
    },
    // 添加意向
    'click #addPotential': function (e, value, row, index) {
        $.ajax({
            url: '/customerController/updatePotentialCustomerByOne',
            type: 'POST',
            datatype: 'json',
            data: {
                customerId: row.customerId,
            },
            success: function (data) {
                if (data.code == '000000') {
                    $.alert({
                        title: '系统提醒',
                        content: '已成功设置为意向客户！',
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $('#dataInfo').bootstrapTable('refresh');
                                }
                            }
                        }
                    })
                }
            }
        })
    },
    // 移除意向
    'click #removePotential': function (e, value, row, index) {
        $.alert({
            title: '系统提醒',
            content: '确定要移除意向客户吗？',
            buttons: {
                cancel: {
                    text: '取消',
                    btnClass: 'btn-link',
                },
                confirm: {
                    text: '移除',
                    btnClass: 'btn-danger',
                    action: function () {
                        $.ajax({
                            url: '/customerController/updatePotentialCustomerByZero',
                            type: 'POST',
                            datatype: 'json',
                            data: {
                                customerId: row.customerId,
                            },
                            success: function (data) {
                                if (data.code == '000000') {
                                    console.log(data, '移除成功');
                                    $('#dataInfo').bootstrapTable('refresh');
                                }
                            }
                        })
                    }
                }
            }
        })

    }
};
function indexOf(val, arr){
    for(var i = 0; i < arr.length; i++){
        if(arr[i] == val){return i;}
    }
    return -1;
}
function remove(val, arr){
    var index = indexOf(val, arr);
    if(index > -1){arr.splice(index,1);}
}

/**
 * 我的客户(企业客户)--客户名称列点击事件(客户详情)
 * @param customerId
 */
function customerDetail (customerId) {
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '客户详情',
        url : "/front/user/customerManager/customerDetail?customerId=" + customerId
    }, true);
}

/**
 * 我的客户(个人客户)--客户名称列点击事件(客户详情)
 * @param customerName
 * @param contactPersonPhone
 */
function contactNameDetail (customerName, contactPersonPhone, customerId) {
    var contactId = "";

    //查询联系人id,进行跳转
    $.ajax({
        url: '/contact/getCustomerIdAndContactNameAndAccountId',
        type: 'POST',
        dataType: "json",
        data: {
            customerId,
            contactName: customerName,
            contactInformation : contactPersonPhone,
            contactNature : '1'
        },
        success: (function (data) {
            if (data.code == "000000") {
                if (data.data.contactId != null) {
                    contactId = data.data.contactId;
                    parent.$(parent.document).data('multitabs').create({
                        iframe: true,
                        title: '联系人详情',
                        url: "/front/user/contactManager/contactDetail?contactId=" + contactId
                    },true);
                }else{
                    $.alert("数据有问题,请重试!");
                }
            } else {
                alert("操作失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}

/**
 * 我的客户--(操作列)跟进跳转
 * @param name 跟进方式：1-线上电话；2-拜访 3-微信 4-线下电话 5-邮箱 6-陪访
 * @param id 客户ID
 * @param customerType 客户类型  0企业客户 1个人客户
 * @param customerName 客户名称
 * @param contactPersonPhone 联系方式
 */
function goOnline(name, id, customerType, customerName, contactPersonPhone) {
    //var poolId = $('#poolId').val();
    var customerId = id;
    var type = '';
    var title = '跟进';
    var source = '1';//从哪跳转到跟进页面（0：线索；1：客户）
    // 线上电话
    if (name == 'online') {
        type = "1";
        title = '客户跟进-线上电话';
    }
    // 拜访
    if (name == 'visit') {
        type = "2";
        title = '客户跟进-拜访';
    }
    // 微信
    if (name == 'WeChat') {
        type = "3";
        title = '客户跟进-微信交流';
    }
    // 线下电话
    if (name == 'offline') {
        type = "4";
        title = '客户跟进-线下电话';
    }
    // 电子邮件
    if (name == 'email') {
        type="5";
        title = '客户跟进-电子邮件';
    }
    // 陪访
    if (name == 'accompanyingVisit') {
        type = "6";
        title = '客户跟进-陪访';
    }
    if (customerType == 1) {
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : title,
            url : "/front/contactManager/user/clueFollow?type="+ type +"&id="
                + customerId +"&source=" +source + "&customerType=" +customerType
                + "&contactName=" + customerName+ "&contactInformation=" + contactPersonPhone
        }, true);
    } else {
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : title,
            url : "/front/contactManager/user/clueFollow?type="+ type +"&id="
                + customerId +"&source=" +source + "&customerType=" +customerType
        }, true);
    }
}

/**
 * 我的客户--(操作列)跟进-》线上电话
 * @param customerId
 */
function callCenter (customerId, customerType) {
    var contactPersonData = [];
    $.ajax({
        url: "/customerController/selectContacts?customerId=" + customerId,
        type: 'GET',
        datatype: 'json',
        async: true,
        success: function (data) {
            if (data) {
                if (data.code == '000000') {
                    contactPersonData = data.data;
                    // console.log(customerType);
                    window.parent.callModal(customerId, contactPersonData,1, '', customerType);
                }
            }
        }
    });
}

function searchMyCustomerPool(type){
    $('#screenCity, #screenCounty').html('<option value="" selected>不限</option>');
    $('#screenWell input, #screenWell select').val('');
    $('#screenWell .input-group-btn select').val('1').selectpicker('refresh');
    $('#screenWell select').selectpicker('refresh');

    tableScreen('dataInfo', esParams());
}

/**
 * 我的客户--重置高级筛选
 */
function resetCustomerQueryParams(_this){
    let searchForm = '';
    if($(_this).parents('#filterContent').context == document) {
        searchForm = $(_this);
    } else {
        searchForm = $(_this).parents('#filterContent');
    }
    searchForm.find('input[type="text"]').val('');
    searchForm.find('select').find('option:first').prop('selected', 'selected');
    // 刷新下拉菜单selectpicker控件
    searchForm.find('select').selectpicker('refresh');

    // 点击重置按钮时，刷线table内容
    if($(_this).parents('#filterContent').context !== document) {
        dataInfoInit();
    }
}

/**
 * 我的客户--重置
 */
function clearAllData() {
    //客户名称
    $('#customerName').val('');
    //创建时间
    $('#createTmStart').val('');
    $('#createTmEnd').val('');
    //客户标签
    $('#tag').val('');
    // 地区
    $('#area').val('').selectpicker('refresh');

    //联系人数量
    $('#contactPersonCountInp').val('');
    $('#contactPersonCountSel').val(1).selectpicker('refresh');
    //财务人数
    $('#financialNumberInp').val('');
    $('#financialNumberSel').val(1).selectpicker('refresh');
    //参保人数
    $('#insuredNumberInp').val('');
    $('#insuredNumberSel').val(1).selectpicker('refresh');
    //注册资本
    $('#registeredCapitalInp').val('');
    $('#registeredCapitalSel').val(1).selectpicker('refresh');
    //企业规模
    $('#companySizeSel').val('').selectpicker('refresh');
    //会员类型
    $('#memberType').val('').selectpicker('refresh');
    //会员到期时间
    $('#memberExpTime').val('').selectpicker('refresh');
    searchMyCustomerPool('senior');
}

/**
 * 客户--释放
 */
function releaseCustomer() {
    var releaseReason = $('#releaseReason').val();//客户收回原因
    if(!releaseReason){
        $.alert("释放原因不能为空");
        return;
    } else if (releaseReason.length > 255) {
        $.alert("释放原因长度不能大于255个字符！");
        return;
    }
    /*if (membershipExpirationTm) {//会员到期时间
        if (new Date().Format("yyyy-MM-dd").valueOf() <= new Date(membershipExpirationTm).Format("yyyy-MM-dd").valueOf()) {
            $.alert("会员未到期不能释放！");
            return;
        }
    }*/
    $.alert({
        title: '提示',
        content: "确定要释放吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customerController/releaseCustomer",
                        data: {
                            customerId : rowCustomerId,
                            releaseReason : releaseReason,
                            membershipExpirationTm : membershipExpirationTm
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $.alert('释放成功!');
                                //$dataInfo.bootstrapTable('refresh');
                                dataInfoInit();
                            } else if (data.code == 'MNE0001') {//会员未到期不能释放
                                $.alert(data.message);
                            } else if (data.code == 'CL0001') {//客户已锁定
                                $.alert(data.message);
                            } else {
                                $.alert('释放失败!');
                            }
                        },
                        error: function () {
                            $.alert('释放异常，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    });
    $('#releaseCustomerModal').modal('hide');
}

/**
 * 修改客户类别
 */
function updateCustomerState(){
    var customerId = $('#customerId').val();
    var customerState = $('#customerState').val(); // 客户状态
    $.ajax({
        url: '/customerController/updateCustomerState',
        type: 'POST',
        dataType: "json",
        data: {
            "customerId": customerId,
            "customerState": customerState
        },
        success: (function (data) {
            if (data.code == "000000") {
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                $('#customerStatusModel').modal('hide');
                                $("#customerState option").removeAttr("selected");
                                window.location.reload();
                            }
                        }
                    }
                });
            } else {
                $.alert("保存失败");
            }
        }),
        error: (function (res) {
            $.alert("保存异常");
        })
    });
}

/**
 * 客户--删除
 * @param customerId     ---客户主键
 */
function deleteCustomer(customerId) {
    $.alert({
        title: '提示',
        content: "确定要删除吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customerController/deleteCustomer",
                        data: {
                            customerId: customerId
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $.alert('删除成功!');
                                $dataInfo.bootstrapTable('refreshOptions', {pageNumber: 1});
                            } else {
                                $.alert('删除失败!');
                            }
                        },
                        error: function () {
                            $.alert('删除异常，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    })
}

/**
 * 功能：添加标签相关功能
 * */
function tagsModal() {
    $('#tagsTable').bootstrapTable('destroy');
    $('#tagsTable').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerTagsController/tagList',                 // 请求地址
        method: 'post',                                         // 请求方式
        contentType: "application/x-www-form-urlencoded",       // 请求内容类型
        dataType: "json",                                       // 数据类型
        striped: true,                                          // 是否显示行间隔色
        sortable: true,                                         // 是否启用排序
        cache: false,                                           // 是否使用缓存
        showColumns: false,                                     // 显示隐藏列
        showRefresh: false,                                     // 显示刷新按钮
        showToggle: false,                                      // 切换显示样式
        showFooter: false,                                      // 显示Table脚部
        pagination: false,                                      // 是否显示分页
        clickToSelect: false,                                   // 是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,                                 // 最少要显示的列数
        undefinedText: '-',                                     // cell没有值时显示
        uniqueId: 'id',
        idField: 'id',
        queryParams: function (params) {                        // 查询参数
            params.pageSize = 10;
            params.pageIndex = 1;
            return params;
        },
        columns: [
            {title: '标签ID', field: 'id', visible: false},
            {title: '标签名', field: 'tag', align: 'left', valign: 'middle'},
            {title: '操作', field: 'tag', align: 'right', valign: 'middle', width: '80',
                formatter: function (value, row, index) {
                    var html = '<button class="btn btn-default btn-danger" onclick="deleteTags(\'' + row.id + '\');"><i class="mdi mdi-delete"></i>删除</button>';
                    return html;
                }
            },
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {

        },
        onPostBody: function (data) {
            if (data.length == '10') {
                $('#editTags .modal-footer .btn-success').prop('disabled', true);
            } else {
                $('#editTags .modal-footer .btn-success').prop('disabled', false);
            }
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}
// 删除标签
function deleteTags(id) {
    $.ajax({
        url: '/customerTagsController/deleteTag',
        type: 'POST',
        dataType: "json",
        data: {
            id
        },
        success: function (data) {
            if (data.code == '000000') {
                $('#tagsTable').bootstrapTable('removeByUniqueId', id);
            } else {
                $.alert({
                    title: '系统提醒',
                    content: '删除标签出错，请稍后再试！（错误代码：' + data.code + '）'
                })
            }
        },
        error: function (err) {
            console.log(err);
        }
    })
}
// 添加标签
function addTags() {
    $.confirm({
        title: '新增标签',
        content: '<input type="text" placeholder="请输入标签名称，不多于5个字符" class="tags-text form-control" autofocus>',
        buttons: {
            cancel: {
                text: '取消',
                btnClass: 'btn-link'
            },
            formSubmit: {
                text: '提交',
                btnClass: 'btn-green',
                action: function () {
                    var tag = this.$content.find('.tags-text').val();
                    if(!tag){
                        $.alert({
                            title: '系统提醒',
                            content: '请输入标签内容！'
                        });
                        return false;
                    }
                    if (tag.length > 5) {
                        $.alert({
                            title: '系统提醒',
                            content: '标签长度不能超过五个字符，请重新输入！'
                        });
                        return false;
                    }
                    $.ajax({
                        url: '/customerTagsController/addTag',
                        type: 'POST',
                        dataType: "json",
                        contentType: 'application/json;charset=utf-8',
                        data: JSON.stringify({tag}),
                        success: function (data) {
                            if (data.code == '000000') {
                                $('#tagsTable').bootstrapTable('refresh');
                            }else if(data.code == 'CT001'){
                                $.alert({
                                    title: '系统提醒',
                                    content: data.message+'!'
                                })
                            } else if(data.code == 'CT002'){
                                $.alert({
                                    title: '系统提醒',
                                    content: data.message+'!'
                                })
                            } else {
                                $.alert({
                                    title: '系统提醒',
                                    content: '添加标签出错，请稍后再试！（错误代码：' + data.code + '）'
                                })
                            }
                        },
                        error: function (err) {
                            console.log(err);
                        }
                    })
                }
            },
        },
        onContentReady: function () {
            var jc = this;
            this.$content.find('form').on('submit', function (e) {
                e.preventDefault();
                jc.$$formSubmit.trigger('click');
            });
        }
    });
}